//
//  RainURLProtocol.m
//  aa
//
//  Created by 周正华 on 2018/8/17.
//  Copyright © 2018年 前隆金融. All rights reserved.
//

#import "RainURLProtocol.h"
static NSString *rainMarkKey = @"TravinProtocolHandledKey";

@implementation RainURLProtocol
//对js文件做监控
+ (BOOL)canInitWithRequest:(NSURLRequest *)request {
    
    NSString * urlstring = [request.URL absoluteString];
    
    if ([urlstring containsString:@".js"]) {
        //看看是否已经处理过了，防止无限循环
        if ([NSURLProtocol propertyForKey:rainMarkKey inRequest:request]) {
            return NO;
        }
        return YES;
    }
    return NO;
}
//我们可以对request进行处理。例如修改头部信息等。最后返回一个处理后的request实例。
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request {
    NSMutableURLRequest *mutableReqeust = [request mutableCopy];
    [mutableReqeust willChangeValueForKey:@"timeoutInterval"];
    mutableReqeust.timeoutInterval = 30.0f;//设置超时时间为30秒
    [mutableReqeust didChangeValueForKey:@"timeoutInterval"];
    
    [NSURLProtocol setProperty:@YES
                        forKey:rainMarkKey
                     inRequest:mutableReqeust];
    return [mutableReqeust copy];
}
/*
// 如果是，则可以使用缓存数据，通常只需要调用父类的实现即可,默认为YES,而且一般不在这里做事情
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b
{
    return [super requestIsCacheEquivalent:a toRequest:b];
}
*/

- (void)startLoading
{
    NSLog(@"111==%@ timeout %.2f",self.request.URL.absoluteString,self.request.timeoutInterval);
    
    self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:YES];
    
    
//    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
//    self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//    self.sessionTask = [self.session dataTaskWithRequest:self.request];
//    [self.sessionTask resume];
    
}
- (void)stopLoading {
    NSLog(@"222==%@",self.connection.currentRequest.URL.absoluteString);
    
    [self.connection cancel];
     
    
//    [self.sessionTask cancel];
//    [self.session invalidateAndCancel];
    
}

#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"444===%@",connection.currentRequest.URL.absoluteString);
    [self.client URLProtocol:self didFailWithError:error];
}

- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection *)connection{
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
    [self.client URLProtocol:self didReceiveAuthenticationChallenge:challenge];
}

- (void)connection:(NSURLConnection *)connection
didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    [self.client URLProtocol:self didCancelAuthenticationChallenge:challenge];
}


#pragma mark - NSURLConnectionDataDelegate
-(NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{
    if (response != nil) {
        [self.client URLProtocol:self wasRedirectedToRequest:request redirectResponse:response];
    }
    return request;
}

- (void)connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response {
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.client URLProtocol:self didLoadData:data];

}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    return cachedResponse;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"333===%@",connection.currentRequest.URL.absoluteString);
    [[self client] URLProtocolDidFinishLoading:self];
}

#pragma mark- sessionTask
//是否需要拦截
+ (BOOL)canInitWithTask:(NSURLSessionTask *)task {
    NSLog(@"%s",__FUNCTION__);
    if ([task.currentRequest.URL.absoluteString containsString:@".js"]) {
        if ([NSURLProtocol propertyForKey:rainMarkKey inRequest:task.currentRequest]) {
            return NO;
        }
        return YES;
    }
    return NO;
}

#pragma mark - NSURLSessionData Delegate

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error {
    NSLog(@"%s",__FUNCTION__);
    [self.client URLProtocol:self didFailWithError:error];
}

- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
    NSLog(@"%s",__FUNCTION__);
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
willPerformHTTPRedirection:(NSHTTPURLResponse *)response
        newRequest:(NSURLRequest *)request
 completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler {
NSLog(@"%s",__FUNCTION__);
    if (response) {
        [self.client URLProtocol:self wasRedirectedToRequest:request redirectResponse:response];
    }
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
    NSLog(@"%s",__FUNCTION__);
}

- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error {
    NSLog(@"%s",__FUNCTION__);
    if (error == nil) {
        [[self client] URLProtocolDidFinishLoading:self];
    } else {
        [[self client] URLProtocol:self didFailWithError:error];
    }
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    NSLog(@"%s",__FUNCTION__);
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed];
    
    if (completionHandler) {
        completionHandler(NSURLSessionResponseAllow);
    }
}

- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
    NSLog(@"%s",__FUNCTION__);
    [self.client URLProtocol:self didLoadData:data];
}

@end
